import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

/*
一般情况我们都是监听别人给我们的数据流，比如 File("").openRead() 读取文件, 刚才给大家讲了
Stream.periodic 可以创建数据流，如果我们想创建更精确的数据流的话也可以使用
StreamController
 */
class StreamControllerDemo extends StatefulWidget {
  @override
  State<StreamControllerDemo> createState() => _DemoPageState();
}

class _DemoPageState extends State<StreamControllerDemo> {
// 定义一个类型为int的Stream
  final _controller = StreamController<int>();

  @override
  void dispose() {
    super.dispose();
    _controller.close();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Stream Demo"),
      ),
      body: Wrap(
        spacing: 20,
        children: [
          ElevatedButton(
// 按钮点击后Stream会释放出数字1
            child: const Text("Emit 1"),
            onPressed: () => _controller.add(1),
          ),
          ElevatedButton(
// 按钮点击后Stream会释放出数字2
            child: const Text("Emit 2"),
            onPressed: () => _controller.add(2),
          ),
          ElevatedButton(
// 按钮点击后Stream会释放出一个错误
            child: const Text("Emit Error"),
            onPressed: () => _controller.addError("oops"),
          ),
          ElevatedButton(
// 按钮点击后Stream会关闭
            child: const Text("Close"),
            onPressed: () => _controller.close(),
          ),
          StreamBuilder(
            stream: _controller.stream,
            builder: (context, snapshot) {
              print("正在重新绘制StreamBuilder组件…");
              if (snapshot.connectionState == ConnectionState.done) {
                return const Text("数据流已关闭");
              }
              if (snapshot.hasError) return Text("${snapshot.error}");
              if (snapshot.hasData) return Text("${snapshot.data}");
              return const Center(
                child: CupertinoActivityIndicator(
                  radius: 40,
                ),
              );
            },
          )
        ],
      ),
    );
  }
}
